import { useReducer } from 'react';

/** 定义初始状态信息  */
interface IstateType {
  needJsonList: Record<string, any>;
  tableData: Record<string, any>[];
}

/** reducer 枚举类型 */
enum INeedActionEnum {
  NEED_JSONLIST = 'need_jsonList',
  SET_tableData = 'SET_tableData',
}

/**
 * 定义页面操作匹配
 * @type 操作类型
 * @payload 传递数据
 */
interface IActionType {
  type: INeedActionEnum;
  payload?: any;
}

/** 定义供应商状态管理 */
const useNeedReducer = () => {
  /** 初始化状态 */
  const initState: IstateType = {
    needJsonList: {},
    tableData: [],
  };

  /** 状态管理逻辑处理 */
  const updateReducer = (state: IstateType, action: IActionType) => {
    switch (action?.type) {
      /** 处理列表数据 */
      case INeedActionEnum.NEED_JSONLIST:
        return {
          ...state,
          needJsonList: action.payload,
        };
      /** 最新的表格数据 */
      case INeedActionEnum.SET_tableData:
        return {
          ...state,
          tableData: action.payload,
        };
      default:
        return {
          ...state,
          ...initState,
        };
    }
  };

  const [state, needDispatch] = useReducer(updateReducer, initState);

  return {
    ...state,
    needDispatch,
  };
};

export { useNeedReducer, INeedActionEnum };
